<template>
  <el-form ref="ruleFormRef" :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px">
    <el-form-item label="主题" prop="title">
      <el-input v-model="formData.title" placeholder="请填写主题" maxlength="32" size="small"/>
    </el-form-item>
    <el-form-item label="员工" prop="staffId">
      <el-select v-model="formData.staffId" placeholder="请选择员工" size="small" filterable>
        <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="培训课程" prop="trainCourse">
      <el-input v-model="formData.trainCourse" placeholder="请填写培训课程" size="small" />
    </el-form-item>
    <el-form-item label="培训机构" prop="trainOrg">
      <el-input v-model="formData.trainOrg" placeholder="请填写培训机构" size="small" />
    </el-form-item>
    <el-form-item label="培训日期" prop="occurDate">
      <el-date-picker
          v-model="trainDateRange"
          type="daterange"
          size="small"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="dateChange"/>
    </el-form-item>
    <el-form-item label="培训时长" prop="trainDuration">
      <el-input v-model="formData.trainDuration" placeholder="请填写培训时长" size="small" />
    </el-form-item>
    <el-form-item label="培训成绩" prop="score">
      <el-input v-model="formData.score" placeholder="请填写培训成绩" size="small"/>
    </el-form-item>
    <el-form-item label="证书名称" prop="certName">
      <el-input v-model="formData.certName" placeholder="请填写证书名称" size="small" />
    </el-form-item>
    <el-form-item label="优先度">
      <el-radio-group v-model="formData.priority" size="small">
        <el-radio :label="0" size="small">普通</el-radio>
        <el-radio :label="1" size="small">高</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注信息" prop="remark">
      <el-input v-model="formData.remark" placeholder="请填写备注信息" type="textarea" :rows="3" size="small" />
    </el-form-item>
  </el-form>
</template>

<script>
// 培训记录 OA_TRAIN_RECORD
import {onMounted, reactive, toRefs, ref, nextTick, watch} from 'vue'
import {formatDate} from '/@/utils/formatTime'
import {getSelectorData} from '/@/api/oa/staff'
import {homeApi} from "/@/api/home/index";
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
  name: 'TrainRecord',
  props: {
    selectTime: {
      type: String,
      default: null
    },
    editId: {
      type: String,
      default: null
    }
  },
  setup(props, context) {
    const { editId, selectTime } = toRefs(props)
    const homeCalendar = homeApi();
    const ruleFormRef = ref()
    const storesCalendarConfig = useCalendarConfig();
    const { eventForm } = storeToRefs(storesCalendarConfig)
    const state = reactive({
      formData: {
        title: '培训记录',
        staffId: null,
        occurDate: null,  // 培训开始日期
        endDate: null,    // 培训结束日期
        trainCourse: null,  // 培训课程
        trainOrg: null,   // 培训机构名称
        trainDuration: null, // 培训时长
        score: null,  // 培训成绩
        certName: null,  // 证书名称
        remark: null,   // 备注信息
        state: 2,           // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
        priority: 0        // 优先级 0普通 1重要
      },
      formRules: {
        title: {required: true, message: '请填写培训记录', trigger: 'blur'},
        staffId: {required: true, message: '请选择员工', trigger: 'change'},
        occurDate: {required: true, message: '请选择培训日期', trigger: 'change'},
        trainCourse: {required: true, message: '请填写培训课程', trigger: 'blur'},
        trainOrg: {required: true, message: '请填写培训机构', trigger: 'blur'},
        trainDuration: {required: true, message: '请填写培训时长', trigger: 'blur'},
        score: {required: true, message: '请填写培训成绩', trigger: 'blur'},
        certName: {required: true, message: '请填写证书名称', trigger: 'blur'}
      },
      trainDateRange: [],
      staffList: [],
      originForm: {}
    })
    const getStaffData = async () => {
      try {
        const res = await getSelectorData()
        state.staffList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const dateChange = val => {
      if (val && val.length == 2) {
        state.formData.occurDate = val[0]
        state.formData.endDate = val[1]
      } else {
        state.formData.occurDate = state.formData.endDate = null
      }
    }
    const submit = () => {
      if(!ruleFormRef) return
       return new Promise(async (resolve, reject) => {
        await ruleFormRef.value.validate((valid, fields) => {
          if (valid) {
              if(editId.value) {
                // 编辑
                for(let key in state.formData){
                  if(state.originForm.hasOwnProperty(key)){
                    state.originForm[key] = state.formData[key]
                  }
                  if(state.originForm.info.hasOwnProperty(key)){
                    state.originForm.info[key] = state.formData[key]
                  }
                }
                storesCalendarConfig.setEventForm(state.originForm)
                reset()
                close()
                resolve('edit') 
              }else{
                homeCalendar.addTrainRecord(state.formData).then((res) => {
                    if (res.code === 0) {
                        reset()
                        close()
                        resolve()
                    }
                });
              }
          } else {
              reject()
              console.log("error submit!", fields);
          }
        })  
       })
    }
    const reset = () => {
      if (!ruleFormRef) return
      ruleFormRef.value.resetFields()
    }
    watch(() => eventForm.value,
      val => {
        if(editId.value && val) {
          // 编辑
          nextTick(() => {
            const data = val
            if(!data) return
            state.originForm = data
            for(let params in data.info){
              // 拿出info里面的数据
              if(state.formData.hasOwnProperty(params)) {
                state.formData[params] = data.info[params]
              }
            }
            for(let key in data) {
              // 列表里面的数据
              if(state.formData.hasOwnProperty(key)) {
                state.formData[key]= data[key]
              }
            }
            if(data.info.occurDate && data.info.endDate) {
              state.trainDateRange = [data.info.occurDate, data.info.endDate]
            }
          })
        }
      }        
    )
    onMounted(() => {
      // 合同编号 毫秒时间戳+5位随机串
      state.formData.contractCode = formatDate(new Date(), 'YYYYmmddHHMMSSsss') + Math.round(Math.random() * (99999 - 10000) + 10000)
      getStaffData()
      nextTick(() => {
        if(!editId.value && selectTime.value) {
          state.formData.occurDate = selectTime.value.substring(0, 10)
          state.formData.endDate = state.formData.occurDate
          state.trainDateRange = [state.formData.occurDate, state.formData.occurDate]
        }
      })
    })

    return {
      ...toRefs(state),
      getStaffData,
      dateChange,
      ruleFormRef,
      submit,
      reset
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
